"""
This example expands on the print_packets example. It checks for HTTP request headers and displays their contents.
NOTE: We are not reconstructing 'flows' so the request (and response if you tried to parse it) will only
      parse correctly if they fit within a single packet. Requests can often fit in a single packet but
      Responses almost never will. For proper reconstruction of flows you may want to look at other projects
      that use DPKT (http://chains.readthedocs.io and others)
"""
import dpkt
import datetime
from dpkt.utils import mac_to_str, inet_to_str


def print_http_requests(pcap):
    """Print out information about each packet in a pcap

       Args:
           pcap: dpkt pcap reader object (dpkt.pcap.Reader)
    """
    # For each packet in the pcap process the contents
    for timestamp, buf in pcap:

        # Unpack the Ethernet frame (mac src/dst, ethertype)
        eth = dpkt.ethernet.Ethernet(buf)

        # Make sure the Ethernet data contains an IP packet
        if not isinstance(eth.data, dpkt.ip.IP):
            print('Non IP Packet type not supported %s\n' % eth.data.__class__.__name__)
            continue

        # Now grab the data within the Ethernet frame (the IP packet)
        ip = eth.data

        # Check for TCP in the transport layer
        if isinstance(ip.data, dpkt.tcp.TCP):

            # Set the TCP data
            tcp = ip.data
            time = str(datetime.datetime.utcfromtimestamp(timestamp))
            print('Timestamp: ', time)
            print('Ethernet Frame: ', mac_to_str(eth.src), mac_to_str(eth.dst), eth.type)
            do_not_fragment = bool(ip.off & dpkt.ip.IP_DF)
            more_fragments = bool(ip.off & dpkt.ip.IP_MF)
            fragment_offset = ip.off & dpkt.ip.IP_OFFMASK
            print('IP: %s -> %s   (len=%d ttl=%d DF=%d MF=%d offset=%d)\n' %
                  (inet_to_str(ip.src), inet_to_str(ip.dst), ip.len, ip.ttl, do_not_fragment, more_fragments,
                   fragment_offset))
            try:
                request = dpkt.ssl.TLSClientHello(tcp.data)
            except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError):
                continue

            # Pull out fragment information (flags and offset all packed into off field, so use bitmasks)


            # Print out the info


            print('HTTP request: %s\n' % repr(request))

            # Check for Header spanning acrossed TCP segments
            if not tcp.data.endswith(b'\r\n'):
                print('\nHEADER TRUNCATED! Reassemble TCP segments!\n')

def parse_tls_pcap(pcap_file_path):
    try:
        with open(pcap_file_path, 'rb') as f:
            pcap = dpkt.pcap.Reader(f)

            for ts, buf in pcap:
                try:
                    eth = dpkt.ethernet.Ethernet(buf)
                    if isinstance(eth.data, dpkt.ip.IP):
                        ip = eth.data
                        if isinstance(ip.data, dpkt.tcp.TCP):
                            tcp = ip.data
                            if tcp.dport == 443 or tcp.sport == 443:
                                try:
                                    tls_records = dpkt.ssl.tls_multi_factory(tcp.data)
                                    for tls_record in tls_records:
                                        print(f"Timestamp: {ts}")
                                        print(f"Version: {hex(tls_record.version)}")
                                        print(f"Type: {tls_record.type}")
                                        print(f"Length: {tls_record.len}")
                                        print("-" * 50)
                                except dpkt.ssl.SSL3Exception:
                                    continue
                except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError):
                    continue
    except FileNotFoundError:
        print(f"Error: The file {pcap_file_path} was not found.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

def test():
    """Open up a test pcap file and print out the packets"""
    with open('tls.pcap', 'rb') as f:
        pcap = dpkt.pcap.Reader(f)
        print_http_requests(pcap)


if __name__ == '__main__':
    parse_tls_pcap('tls.pcap')